/*
 * @Descripttion: 
 * @Author: voanit
 * @Date: 2022-06-08 15:53:12
 * @LastEditors: voanit
 * @LastEditTime: 2022-06-08 16:04:20
 */
import classnames from 'classnames'
import { useRef } from 'react'
import Icon from '../Icon/Icon'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
/**
 * 拥有懒加载特性的图片组件
 * @param {String} props.src 图片地址
 * @param {String} props.className 样式类
 */
type Props = {
  src: string
  className?: string
}
const Image = ({ src, className }: Props) => {
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)
  // 对图片元素的引用
  const imgRef = useRef<HTMLImageElement>(null)
  useEffect(() => {
    const ob = new IntersectionObserver(
      (entries) => {
        console.log('working....')
        if (entries[0].isIntersecting) {
          imgRef.current!.src = src
          ob.unobserve(imgRef.current!)
        }
      },
      { rootMargin: '300px' }
    )

    ob.observe(imgRef.current!)
    /* 销毁 */
    return () => {
      ob.disconnect()
    }
  }, [src])

  return (
    <div className={classnames(styles.root, className)}>
      {/* 正在加载时显示的内容 */}

      {
        loading && (<div className="image-icon">
          <Icon type="iconphoto" />
        </div>)

      }

      {/* 加载出错时显示的内容 */}
      {
        error && (<div className="image-icon">
          <Icon type="iconphoto-fail" />
        </div>)
      }

      {/* 加载成功时显示的内容 */}
      {<img onError={() => setError(true)}
        onLoad={() => setLoading(false)} alt="" data-src={src} ref={imgRef} />}
    </div >
  )
}

export default Image